package com.simple.tools.aab2apks;

import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Properties;

public class SettingsController {
    private static final Logger logger = LoggerFactory.getLogger(SettingsController.class);

    @FXML private TextField bundletoolDownloadPathField;
    @FXML private Label currentVersionLabel;
    @FXML private ProgressBar updateProgressBar;
    @FXML private Label updateStatusLabel;

    private static final String VERSION = "1.0.0"; // Replace with your actual version
    private static final String UPDATE_URL = "https://example.com/update.json"; // Replace with your actual update URL
    private static final String SETTINGS_FILE = "settings.properties";

    private Properties settings;

    @FXML
    private void initialize() {
        currentVersionLabel.setText(VERSION);
        loadSettings();
    }

    private void loadSettings() {
        settings = new Properties();
        try (InputStream input = new FileInputStream(SETTINGS_FILE)) {
            settings.load(input);
            bundletoolDownloadPathField.setText(settings.getProperty("bundletoolDownloadPath", System.getProperty("user.home") + "/.aab2apk"));
        } catch (IOException ex) {
            logger.error("Could not load settings", ex);
        }
    }

    @FXML
    private void onSelectBundletoolDownloadPath() {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("Select Bundletool Download Location");
        File selectedDir = directoryChooser.showDialog(null);
        if (selectedDir != null) {
            bundletoolDownloadPathField.setText(selectedDir.getAbsolutePath());
        }
    }

    @FXML
    private void onCheckForUpdates() {
        updateProgressBar.setVisible(true);
        updateStatusLabel.setText("Checking for updates...");

        new Thread(() -> {
            try {
                URL url = new URL(UPDATE_URL);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String latestVersion = reader.readLine();
                    reader.close();

                    if (isNewerVersion(latestVersion)) {
                        javafx.application.Platform.runLater(() -> {
                            updateStatusLabel.setText("New version available: " + latestVersion);
                            // Here you would typically prompt the user and start the download
                            // For simplicity, we'll just show a message
                        });
                    } else {
                        javafx.application.Platform.runLater(() -> {
                            updateStatusLabel.setText("You have the latest version.");
                        });
                    }
                } else {
                    javafx.application.Platform.runLater(() -> {
                        updateStatusLabel.setText("Failed to check for updates.");
                    });
                }
            } catch (IOException e) {
                logger.error("Error checking for updates", e);
                javafx.application.Platform.runLater(() -> {
                    updateStatusLabel.setText("Error checking for updates: " + e.getMessage());
                });
            } finally {
                javafx.application.Platform.runLater(() -> {
                    updateProgressBar.setVisible(false);
                });
            }
        }).start();
    }

    private boolean isNewerVersion(String latestVersion) {
        // Implement version comparison logic here
        // For simplicity, we'll just do a string comparison
        return latestVersion.compareTo(VERSION) > 0;
    }

    @FXML
    private void onSaveAndClose() {
        settings.setProperty("bundletoolDownloadPath", bundletoolDownloadPathField.getText());
        try (OutputStream output = new FileOutputStream(SETTINGS_FILE)) {
            settings.store(output, null);
        } catch (IOException ex) {
            logger.error("Could not save settings", ex);
        }

        Stage stage = (Stage) bundletoolDownloadPathField.getScene().getWindow();
        stage.close();
    }
}